package com.gopay.scheduler.service.jobmonitor.impl;

import com.gopay.common.constants.cust.SMSType;
import com.gopay.scheduler.GopaySchedulerFactory;
import com.gopay.scheduler.common.SendMsg;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * Created by liyang on 2017/3/23.
 */
@Component("cronSchedulerListener")
public class CronSchedulerListener implements SchedulerListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "sendMsg")
    private SendMsg sendMsg;

    @Value("#{webProperties['jobCron.recvMobile']}")
    private String recvMobile;

    @Value("#{webProperties['jobCron.sms.switch']}")
    private String jobCronSwitch;

    private static final String SWITCH_ON = "on";

    private static Integer sendMsgTimes = 0;
    @Override
    public void jobScheduled(Trigger trigger) {
    }

    @Override
    public void jobUnscheduled(TriggerKey triggerKey) {

    }

    @Override
    public void triggerFinalized(Trigger trigger) {

    }

    @Override
    public void triggerPaused(TriggerKey triggerKey) {

    }

    @Override
    public void triggersPaused(String s) {

    }

    @Override
    public void triggerResumed(TriggerKey triggerKey) {

    }

    @Override
    public void triggersResumed(String s) {

    }

    @Override
    public void jobAdded(JobDetail jobDetail) {

    }

    @Override
    public void jobDeleted(JobKey jobKey) {

    }

    @Override
    public void jobPaused(JobKey jobKey) {

    }

    @Override
    public void jobsPaused(String s) {

    }

    @Override
    public void jobResumed(JobKey jobKey) {

    }

    @Override
    public void jobsResumed(String s) {

    }

    @Override
    public void schedulerError(String s, SchedulerException e) {
        try {
            logger.error("quartz调度器出现异常！！,errMsg=" + e);
            sendMsgTimes++;
            if (sendMsgTimes <= 1) {
                if (SWITCH_ON.equals(jobCronSwitch)) {
                    sendMsg.sendSms(recvMobile, String.format("定时任务调度器(生产%s)在%s出现异常，请您处理！！异常描述：%s", GopaySchedulerFactory.switchType, new Date(), s), SMSType.OTHER_SMS);
                }
            } else {
                logger.info(String.format("cron预警短信已关闭：定时任务调度器在%s出现异常，请您处理！！", new Date()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void schedulerInStandbyMode() {

    }

    @Override
    public void schedulerStarted() {
        logger.info("调度器启动成功！！");
    }

    @Override
    public void schedulerStarting() {

    }

    @Override
    public void schedulerShutdown() {

    }

    @Override
    public void schedulerShuttingdown() {

    }

    @Override
    public void schedulingDataCleared() {

    }
}
